// 子模块cart路径：store/cart.js
export default {
	// 开启命名空间
	namespaced: true,
	
	state: {
		// 购物车数据
		cart:JSON.parse(uni.getStorageSync('cart')||'[]'),
	},
	getters: {
		// 计算购物车总数
		total(state){
			// let c=0
			// state.cart.forEach(x=>c+=x.goods_count)
			// return c
			if(JSON.stringify(state.cart)==='{}'){
				return
			}
			else{
				return state.cart.reduce((total,item)=>total+=item.goods_count,0)
			}
		},
		
		// 计算选中的商品数量
		checkedCount(state){
			return state.cart.filter(x=>x.goods_state).reduce((total,item)=> total+=item.goods_count,0)
		},
		
		// 计算选中商品的价格
		checkedCountPrice(state){
			return state.cart.filter(x=>x.goods_state).reduce((total,item)=> total+=item.goods_count*item.goods_price,0).toFixed(2)
		}
	},
	mutations: {
		// 添加商品购物车详细信息在state中的Cart
		addToCart(state,goods){
			const findResult = state.cart.find(x=>x.goods_id===goods.goods_id)
			if(!findResult){
				state.cart.push(goods)
			}else{
				findResult.goods_count++
			}
			// 调用持久化数据方法
			this.commit('my_cart/saveToStorage')
		},
		// 持久化购物车数据
		saveToStorage(state){
			uni.setStorage({
				key:'cart',
				data:JSON.stringify(state.cart)
			})
		},
		// 更新商品选中状态数据
		updateCartListStateData(state,newState){
			const findResult = state.cart.find(x=>x.goods_id===newState.goods_id)
			if(findResult){
				findResult.goods_state=newState.goods_state
				this.commit('my_cart/saveToStorage')
			}
		},
		// 更新商品选中Count数据
		updateCartListCountData(state,newCount){
			const findResult = state.cart.find(x=>x.goods_id===newCount.goods_id)
			if(findResult){
				findResult.goods_count=newCount.goods_count
				this.commit('my_cart/saveToStorage')
			}
		},
		// 删除商品
		deleteCartListData(state,goodsId){
			state.cart = state.cart.filter(x=>x.goods_id!==goodsId.goods_id)
			this.commit('my_cart/saveToStorage')
		},
		// 更新单选框全选或反选
		updateRadioChangeHandle(state,value){
			state.cart.forEach(x=>x.goods_state=value)
			this.commit('my_cart/saveToStorage')
		}
	},
	actions: {

	}
}